package com.chat.handler;

import com.netty.imp.IMMessage;
import com.netty.imp.IMP;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Objects;

/**
 * @author kewei
 */
public class HeartBeatClientHandler extends SimpleChannelInboundHandler<IMMessage> {

    private String nickName;

    public HeartBeatClientHandler(String nickName) {
        this.nickName = nickName;
    }

    /**
     * Is called for each message of type {@link I}.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, IMMessage msg) throws Exception {
        if (Objects.isNull(msg) || IMP.CLOSE.name().equals(msg.getCmd())) {
            System.out.println(" ====== > [client][HeartBeatClientHandler] message received : " + msg.getContent());
            ctx.channel().closeFuture();
            ctx.close();
        } else if (IMP.PONG.name().equals(msg.getCmd())) {
            //服务端对心跳的回应
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("心跳检测");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (ctx.channel().isActive()) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ctx.channel().writeAndFlush(new IMMessage(IMP.PING.name(), System.currentTimeMillis(), nickName, "I am alive"));
                }
                ctx.channel().closeFuture();
            }
        }).start();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("Client异常:" + channel.remoteAddress());
        cause.printStackTrace();
        ctx.close();
    }
}
